﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Security.Cryptography;
using System.Globalization;
using System.Text.RegularExpressions;


/// <summary>
/// Descripción breve de Utility
/// </summary>
public class Utility
{
     
	public Utility()
	{
		//
		// TODO: Agregar aquí la lógica del constructor
		//
	}

    public static string cifrado(string texto)
    {
        string result = null;
        try
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(texto);
            bs = x.ComputeHash(bs);
            string password;
            System.Text.StringBuilder smd = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                smd.Append(b.ToString("x2").ToLower());
            }
            result = smd.ToString();
        }
        catch (Exception e)
        {

            return null;
        }
        return result;

    }


    //para generar xml
    public static string setXml(string user, string pass, int app, int perfilid)
    {
        string result = "";
        
        result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><datos_login>";
        result = result+ "<usuarioid>";
        result= result+user;
        result = result + "</usuarioid> <contrasena>"+ pass;
        result = result + "</contrasena><aplicacionid>" + app + "</aplicacionid><perfilid>" + perfilid + "</perfilid></datos_login>";
        return result;
                       
        
        }

    
       
    
    

    //para consumir ws de login, lee xml de respuesta
    public static rUser getRUser(string sdatosin)
    {
        rUser ruser = null;

        try
        {
            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatosin));

            XmlElement datosrespuesta = xDoc.DocumentElement;
            ruser = new rUser();
            foreach (XmlElement nodo in datosrespuesta)
            {
                if (nodo.Name.Equals("respuestaid"))
                {

                    int rid = int.Parse(nodo.InnerText);
                    ruser.setRespuestaId(rid);
                }
                if (nodo.Name.Equals("usuarioid"))
                {

                    ruser.setUsuarioId(nodo.InnerText);
                }
                if (nodo.Name.Equals("nombre"))
                {

                    ruser.setNombre(nodo.InnerText);
                }
                if (nodo.Name.Equals("apellido"))
                {

                    ruser.setApellido(nodo.InnerText);
                }
                if (nodo.Name.Equals("alias"))
                {

                    ruser.setAlias(nodo.InnerText);
                }
                if (nodo.Name.Equals("perfilid"))
                {

                    ruser.setPerfilId(nodo.InnerText);
                }
                if (nodo.Name.Equals("permiso"))
                {


                    double rper = double.Parse(nodo.InnerText);
                    ruser.setPermiso(rper.ToString());
                }
                if (nodo.Name.Equals("logo"))
                {

                    ruser.setLogo(nodo.InnerText);
                }
                if (nodo.Name.Equals("email"))
                {

                    ruser.setEmail(nodo.InnerText);
                }

            }
        }
        catch (Exception e)
        {

        }
        return ruser;
}


    public static rReg getRReg(string sdatosreg)
    {
        rReg rreg = new rReg();
        try{

        XmlDocument xDoc = new XmlDocument();

        xDoc.Load(new StringReader(sdatosreg));

        XmlElement datosrespuesta = xDoc.DocumentElement;
        
        
            foreach (XmlElement nodo in datosrespuesta)
            {
                if (nodo.Name.Equals("respuestaid"))
                {

                    int rid = int.Parse(nodo.InnerText);
                    rreg.setRespuestaId(rid);
                }
                if (nodo.Name.Equals("mensaje"))
                {

                    rreg.setMensaje(nodo.InnerText);
                }
                if (nodo.Name.Equals("userid"))
                {

                    int uid = int.Parse(nodo.InnerText);
                    rreg.setUserId(uid);
                }

            }
        }
        catch (Exception e)
        {
            rreg.setRespuestaId(0);
            rreg.setMensaje("Error");

        }
        return rreg;
    }
    public static rActivate getRAct(string sdatosreg)
    {
        rActivate ract = new rActivate();
        try
        {

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatosreg));

            XmlElement datosrespuesta = xDoc.DocumentElement;


            foreach (XmlElement nodo in datosrespuesta)
            {
                if (nodo.Name.Equals("respuestaid"))
                {

                    int rid = int.Parse(nodo.InnerText);
                    ract.setRespuestaId(rid);
                }
                if (nodo.Name.Equals("mensaje"))
                {

                    ract.setMensaje(nodo.InnerText);
                }
               

            }
        }
        catch (Exception e)
        {
            ract.setRespuestaId(0);
            ract.setMensaje("Error");

        }
        return ract;
    }
    
    public static string sendMail(string mailfrom, string mail, string Subject,string body){
        string result;
        result = "";
        try
        {
            if (!mail.Equals(""))
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(mailfrom);

                message.To.Add(new MailAddress(mail));
                message.Subject = Subject;
                message.IsBodyHtml = true;
                message.Body = body;
              
                SmtpClient client = new SmtpClient();
                client.Host = "s2smtpout.secureserver.net";
                client.EnableSsl = false;
                client.UseDefaultCredentials = true;
                client.Port = 25;
                client.Credentials = new NetworkCredential("newclient@bpophotos.com", "photos1");
                client.Send(message);
                result = "ok";
            }
        }
        catch (Exception e) {

            writeError(e.StackTrace);


            result = "";
        }
            return result;
    }
    public static void writeError(string error) {
        try
        {
            string ruta = "c:\\TEMP\\log_bpo.txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(DateTime.Now + " " + error);
            escritor.Close();
        }
        catch (Exception e){
            
        }
    
    }

    public static string sendMailAtach(string mailfrom, string mail, string Subject, string body, string[] attach)
    {
        string result;
        result = "";
        try
        {
            if (!mail.Equals(""))
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(mailfrom);

                message.To.Add(new MailAddress(mail));
                message.Subject = Subject;
                message.IsBodyHtml = true;
                message.Body = body;
                for (int i = 0; i < attach.Length ; i++ ) {
                    if (attach[i]!=null){
                    message.Attachments.Add(new Attachment(@attach[i]));
                    }
                }
               
                SmtpClient client = new SmtpClient();
                client.Host = "s2smtpout.secureserver.net";
                client.EnableSsl = false;
                client.UseDefaultCredentials = true;
                client.Port = 25;
                client.Credentials = new NetworkCredential("newclient@bpophotos.com", "photos1");
                client.Send(message);
                result = "ok";
            }
        }
        catch (Exception e)
        {

            writeError(e.StackTrace);
            
            result = "";
        }
        return result;
    }
    
    public static string ComputeHash(string   plainText,
                                     string   hashAlgorithm,
                                     byte[]   saltBytes)
    {
        // If salt is not specified, generate it on the fly.
        if (saltBytes == null)
        {
            // Define min and max salt sizes.
            int minSaltSize = 4;
            int maxSaltSize = 8;

            // Generate a random number for the size of the salt.
            Random  random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            // Allocate a byte array, which will hold the salt.
            saltBytes = new byte[saltSize];

            // Initialize a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Fill the salt with cryptographically strong byte values.
            rng.GetNonZeroBytes(saltBytes); 
        }
        
        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        
        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithSaltBytes = 
                new byte[plainTextBytes.Length + saltBytes.Length];

        // Copy plain text bytes into resulting array.
        for (int i=0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];
        
        // Append salt bytes to the resulting array.
        for (int i=0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        // Because we support multiple hashing algorithms, we must define
        // hash object as a common (abstract) base class. We will specify the
        // actual hashing algorithm class later during object creation.
        HashAlgorithm hash;
        
        // Make sure hashing algorithm name is specified.
        if (hashAlgorithm == null)
            hashAlgorithm = "";
        
        // Initialize appropriate hashing algorithm class.
        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
        }
        
        // Compute hash value of our plain text with appended salt.
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
        
        // Create array which will hold hash and original salt bytes.
        byte[] hashWithSaltBytes = new byte[hashBytes.Length + 
                                            saltBytes.Length];
        
        // Copy hash bytes into resulting array.
        for (int i=0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];
            
        // Append salt bytes to the result.
        for (int i=0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            
        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);
        
        // Return the result.
        return hashValue;
    }

    /// <summary>
    /// Compares a hash of the specified plain text value to a given hash
    /// value. Plain text is hashed with the same salt value as the original
    /// hash.
    /// </summary>
    /// <param name="plainText">
    /// Plain text to be verified against the specified hash. The function
    /// does not check whether this parameter is null.
    /// </param>
    /// <param name="hashAlgorithm">
    /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", 
    /// "SHA256", "SHA384", and "SHA512" (if any other value is specified,
    /// MD5 hashing algorithm will be used). This value is case-insensitive.
    /// </param>
    /// <param name="hashValue">
    /// Base64-encoded hash value produced by ComputeHash function. This value
    /// includes the original salt appended to it.
    /// </param>
    /// <returns>
    /// If computed hash mathes the specified hash the function the return
    /// value is true; otherwise, the function returns false.
    /// </returns>
    public static bool VerifyHash(string   plainText,
                                  string   hashAlgorithm,
                                  string   hashValue)
    {
        // Convert base64-encoded hash value into a byte array.
        byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
        
        // We must know size of hash (without salt).
        int hashSizeInBits, hashSizeInBytes;
        
        // Make sure that hashing algorithm name is specified.
        if (hashAlgorithm == null)
            hashAlgorithm = "";
        
        // Size of hash is based on the specified algorithm.
        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hashSizeInBits = 160;
                break;

            case "SHA256":
                hashSizeInBits = 256;
                break;

            case "SHA384":
                hashSizeInBits = 384;
                break;

            case "SHA512":
                hashSizeInBits = 512;
                break;

            default: // Must be MD5
                hashSizeInBits = 128;
                break;
        }

        // Convert size of hash from bits to bytes.
        hashSizeInBytes = hashSizeInBits / 8;

        // Make sure that the specified hash value is long enough.
        if (hashWithSaltBytes.Length < hashSizeInBytes)
            return false;

        // Allocate array to hold original salt bytes retrieved from hash.
        byte[] saltBytes = new byte[hashWithSaltBytes.Length - 
                                    hashSizeInBytes];

        // Copy salt from the end of the hash to the new array.
        for (int i=0; i < saltBytes.Length; i++)
            saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];

        // Compute a new hash string.
        string expectedHashString = 
                    ComputeHash(plainText, hashAlgorithm, saltBytes);

        // If the computed hash matches the specified hash,
        // the plain text value must be correct.
        return (hashValue == expectedHashString);
    }
    public static DataSet getUsuariosporPerfil(string sdatos)
    {
        DataSet result= new DataSet();
         result.Tables.Add("Tabla");
         result.Tables["Tabla"].Columns.Add("user");
         result.Tables["Tabla"].Columns.Add("name");
         result.Tables["Tabla"].Columns.Add("lastname");
         result.Tables["Tabla"].Columns.Add("comp-name");
         result.Tables["Tabla"].Columns.Add("alias");
         result.Tables["Tabla"].Columns.Add("email");
        try
        {

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatos));

            XmlElement datosrespuesta = xDoc.DocumentElement;
            
            XmlNodeList users = xDoc.GetElementsByTagName("lista_usuarios");
            XmlNodeList respuesta = xDoc.GetElementsByTagName("respuestaID");

            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("datos_registro");
            
            foreach (XmlElement nodo in lista)
            {
                
                XmlNodeList nUser = nodo.GetElementsByTagName("user");
                XmlNodeList nName = nodo.GetElementsByTagName("name");
                XmlNodeList nLastname = nodo.GetElementsByTagName("lastname");
                XmlNodeList nCompname = nodo.GetElementsByTagName("comp-name");
                XmlNodeList nAlias = nodo.GetElementsByTagName("alias");
                XmlNodeList nEmail = nodo.GetElementsByTagName("email");
                DataRow fila;
                fila= result.Tables[0].NewRow();
                fila["user"] = nUser[0].InnerText;
                fila["name"] = nName[0].InnerText;
                fila["lastname"] = nLastname[0].InnerText;
                fila["comp-name"] = nCompname[0].InnerText;
                fila["alias"] = nAlias[0].InnerText;
                fila["email"] = nEmail[0].InnerText;
                result.Tables[0].Rows.Add(fila);
              

            }
            
        }
        catch (Exception e)
        {
            result = null;
            

        }
        return result;
    }

    public string formatHour(string strin) {
        string result;
        result = DateTime.Parse(strin).Hour.ToString() + ":" + DateTime.Parse(strin).Minute.ToString();
        return result;
    
    }
    public string formatDate(string strin) {
        string result;
        CultureInfo ci = new CultureInfo("en-US");
        result = DateTime.Parse(strin, ci).Date.ToShortDateString();

        return result;
    }
    public static string formatNumber(double fee) {
        string result;

        CultureInfo ci = new CultureInfo("es-GT");
        result = String.Format("{0:#.00}", fee);
        result = result.ToString(ci);

        return result;

    }
   


   public static string HoraAMPMtoFormato24horas(string horaformato12, string AMoPM)
    //convierte una hora en formato AMPM a formato de 24 horas
    {
        string input = horaformato12 + AMoPM,str1=null,str2=null;
        string sresult = null;
        sresult = "00:00";
 
 
        try
        {
 
 
            DateTime time = DateTime.Parse(input);
            int hour24 = int.Parse(time.ToString("HH"));
            int minute = int.Parse(time.ToString("mm"));
            str1 = string.Format("{0}", hour24);
            if (hour24 < 10)
            {
 
                str1 = "0" + str1;
 
            }
            str2 = string.Format("{0}", minute);
            if (minute < 10)
            {
                str2 = "0" + str2;
            }
            sresult = str1 + ":" + str2;
        }
 
        catch (Exception e)
        {
            Console.WriteLine("Error ! Not a valid time format...");
 
        }
       
        return sresult;
    }
    public  static RE_GenericBean Hora24horastoFormatoAMPM(string horaformato)
    //convierte una hora en format 24 horas a formato AMPM   
   {
        RE_GenericBean result=new RE_GenericBean();
        try
        {
 
            string input = horaformato,str1,str2;
            string AMPM = "AM";
            DateTime time = DateTime.Parse(input);
            int hour24 = int.Parse(time.ToString("HH"));
            if (hour24 > 11)
            {
                AMPM = "PM";
                hour24 = hour24 - 12;
            }
            if (hour24 > 23)
            {
                AMPM = "AM";
                hour24 = hour24 - 12;
            }
 
 
            int minute = int.Parse(time.ToString("mm"));
            str1 = string.Format("{0}", hour24);
           
            if (hour24 < 10)
            {
 
                str1 = "0" + str1;
            }
 
            str2 = string.Format("{0}", minute);
            if (minute < 10)
            {
 
                str2 = "0" + str2;
 
            }
 
 
            result.strC1 = str1 + ":" + str2;
            result.strC2 = AMPM;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error ! Not a valid time format...");
 
        }
        return result;
 
    }

    public static bool validarEmail(string email)
    {
        string expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

        if (Regex.IsMatch(email, expresion))
        {
            if (Regex.Replace(email, expresion, String.Empty).Length == 0)
            { return true; }
            else
            { return false; }
        }
        else
        { return false; }
    }
    public static int ValidateDate(string date)
    {
        try
        {

            string[] dateParts = date.Split('/');

            DateTime testDate = new
            DateTime(Convert.ToInt32(dateParts[2]), Convert.ToInt32(dateParts[0]), Convert.ToInt32(dateParts[1]));
            
            return 1;
        }
        catch
        {

            return 0;
        }
    }

    public static int ValidarHora(string hora)
    {
        try
        {


            string[] timeParts = hora.Split(':');

            if (Convert.ToInt32(timeParts[0]) >= 0)
            {
                if (Convert.ToInt32(timeParts[0]) <= 24)
                {
                    if (Convert.ToInt32(timeParts[1]) >= 0)
                    {
                        if (Convert.ToInt32(timeParts[1]) <= 59)
                        {
                            bool isOK = Regex.IsMatch(hora, @"[0-2][0-9]\:[0-6][0-9]");
                            if (isOK)
                            {
                                return 1;

                            }
                        }

                    }

                }
            }
        }
        catch
        {

            return 0;
        }

        return 0;


    }


    public static string getsrtDate(string strdatein) {
        string result = "";
        DateTime re = DateTime.Parse(strdatein);
        result = re.ToShortDateString();
        return result;


    }

    public static string getsrtTime(string strdatein) {
        string result = "";
        DateTime re = DateTime.Parse(strdatein);
        result = re.ToShortDateString();
        return result;
    
    }
    public static DataSet getCompanies(string sdatos)
    {//parsea xml de webservice todas las companias
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("com_id");
        result.Tables["Tabla"].Columns.Add("com_nombre");
      
        try
        {

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatos));

            XmlElement datosrespuesta = xDoc.DocumentElement;

            XmlNodeList users = xDoc.GetElementsByTagName("lista_companies");
            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("datos_company");

            foreach (XmlElement nodo in lista)
            {

                XmlNodeList nUser = nodo.GetElementsByTagName("com_id");
                XmlNodeList nName = nodo.GetElementsByTagName("com_nombre");
              
                DataRow fila;
                fila = result.Tables[0].NewRow();
                fila["com_id"] = nUser[0].InnerText;
                fila["com_nombre"] = nName[0].InnerText;
                result.Tables[0].Rows.Add(fila);


            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.Message + e.StackTrace );
            result = null;


        }
        return result;
    }


    public static string QuitarCaracteresNoNumericos(string cadena)
    {

        int cont = 0;

        string numeros = "0123456789";

        string cadenaResult = "";



        while (cont < cadena.Length)
        {

            int cont2 = 0;

            while (cont2 < numeros.Length)
            {

                if (cadena[cont] == numeros[cont2])

                    cadenaResult = cadenaResult + cadena[cont];

                cont2++;

            }

            cont++;

        }

        return cadenaResult;

    }

    public static DataSet getAccounts(string sdatos)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("acc_id");
        result.Tables["Tabla"].Columns.Add("acc_nombre");
        result.Tables["Tabla"].Columns.Add("acc_initial");

        try
        {

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatos));

            XmlElement datosrespuesta = xDoc.DocumentElement;

            XmlNodeList users = xDoc.GetElementsByTagName("lista_account");
            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("datos_account");

            foreach (XmlElement nodo in lista)
            {

                XmlNodeList nUser = nodo.GetElementsByTagName("acc_id");
                XmlNodeList nName = nodo.GetElementsByTagName("acc_nombre");
                XmlNodeList nInitial = nodo.GetElementsByTagName("acc_initial");

                DataRow fila;
                fila = result.Tables[0].NewRow();
                fila["acc_id"] = nUser[0].InnerText;
                fila["acc_nombre"] = nName[0].InnerText;
                fila["acc_initial"] = nInitial[0].InnerText;

                result.Tables[0].Rows.Add(fila);


            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.Message + e.StackTrace);
            result = null;


        }
        return result;
    }

    public static string toCapital(string strin) {


        int cont = 0;
        string result = "";
        bool encontrado = false;

        strin = strin.TrimStart();
        strin = strin.TrimEnd();

        string[] cad = strin.Split(' ');


        for (int aux = 0; aux < strin.Length; aux++)
        {
            if (strin[aux] == ' ')
            {
                encontrado = true;
            }
        }


        if (strin != null)
        {
            if (encontrado == true)
            {
                while (cont < cad.Length)
                {
                    if (cad[cont] != "")
                        result = result + " " + cad[cont].ToUpper().Substring(0, 1) + cad[cont].ToLower().Substring(1, cad[cont].ToString().Length - 1);

                    cont++;
                }
            }
            else
            {
                if (strin == "")
                    result = "";
                else
                    result = strin.ToUpper().Substring(0, 1) + strin.ToLower().Substring(1, strin.ToString().Length - 1);
            }
        }
        else
            result = "";

        return result;

    
    
    }
   
}

